package cn.edu.nju.newsFeed;

import java.util.List;

import cn.edu.nju.R;
import android.app.Activity;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CommentListAdapter extends BaseAdapter{
	private Activity context;
	private ListItemFormatHelper helper;
	private NewsFeedItem feedItem;
	private List<CommentItem> items;
	private FeedClickableSpan likeSpan;
	
	public CommentListAdapter(NewsFeedDetailActivity activity, NewsFeedItem item){
		this.context = activity;
		this.helper = new ListItemFormatHelper(activity);
		this.feedItem = item;
		this.items = item.getComments();
		
		initTextSpans();
	}
	
	private void initTextSpans(){
		likeSpan = new FeedClickableSpan(context) {			
			@Override
			public void onClick(View widget) {
				int position = (Integer)widget.getTag(R.id.VIEW_POSITION_TAG);
				CommentItem item = getItem(position);
				item.addOneLike();
				helper.setLikeNumberText((TextView)widget, item, likeSpan);
			}
		};
	}
	
	public int getCount(){
		return items.size();
	}
	
	public CommentItem getItem(int position){
		return items.get(position);
	}
	
	public long getItemId(int position){
		return position;
	}
	
	public View getView(int position, View convertView, ViewGroup parent) {
		View resultView = null;
		CommentItemCache viewCache = null;
		if(convertView == null){
			LayoutInflater inflater = context.getLayoutInflater();
			resultView = inflater.inflate(R.layout.comment_item, null);
			viewCache = new CommentItemCache(resultView);
			resultView.setTag(R.id.VIEW_CACHE_TAG, viewCache);
		} else{
			resultView = convertView;
			viewCache = (CommentItemCache)resultView.getTag(R.id.VIEW_CACHE_TAG);
		}
		
		CommentItem item = getItem(position);
		
		ImageView avatarView = viewCache.getAvatarView();
		helper.setAvatar(avatarView, item);
		
		TextView contentView = viewCache.getContentView();
		contentView.setTag(R.id.VIEW_POSITION_TAG, position);
		helper.setContentText(contentView, item, null, null);
		
		TextView timeView = viewCache.getTimeView();
		helper.setTimeText(timeView, item);
		
		TextView likeNumberView = viewCache.getLikeNumberView();
		likeNumberView.setTag(R.id.VIEW_POSITION_TAG, position);
		likeNumberView.setMovementMethod(LinkMovementMethod.getInstance());
		helper.setLikeNumberText(likeNumberView, item, likeSpan);

		return resultView;
	}
	
	public void refresh(){
		this.items = feedItem.getComments();
		notifyDataSetChanged();
	}
}
